<template>
	<!-- 顶部导航栏（紧凑版） -->
	<view class="navbar">
		<!-- Logo -->
		<view class="logo">
			<image src="/img/爱淘宝 (1).svg" style="width: 48rpx; height: 48rpx;" mode="aspectFit" />
		</view>
		<!-- 搜索框 -->
		<view class="search-box" @click="goSearch">
			<view class="fake-search">
				<wd-icon name="search" size="18px" color="#999" />
				<text class="fake-search-text">搜索商品</text>
			</view>
		</view>
	</view>
	<!-- 轮播图 -->
	<view>
		<wd-swiper :list="swiperList.map(item => item.img)" autoplay v-model:current="current" @click="handleClick"
			@change="onChange" height="500rpx"></wd-swiper>
	</view>

	<!-- 标签图标区域 -->
	<view class="icon-section">
		<!-- 图标行 -->
		<view class="icon-row">
			<view class="icon-item" v-for="(item, index) in iconList" :key="index">
				<image class="icon-image" :src="item.img" mode="aspectFill"></image>
				<text class="icon-text">{{ item.text }}</text>
			</view>
		</view>
	</view>

	<!-- 分割线 -->
	<wd-divider>为你推荐</wd-divider>

	<!-- 商品列表模板部分 -->
	<view class="product-list">
		<view class="product-item" v-for="(item, index) in productList" :key="item.id"
			@click="handleProductClick(item)">
			<image
				class="product-image"
				:src="item.img_url || item.image || '/static/logo.png'"
				mode="aspectFit"
				@error="e => console.log('商品图片加载失败', item.img_url || item.image)"
			></image>
			<view class="product-info">
				<text class="product-title">{{ item.title }}</text>
				<view class="price-section">
					<text class="product-price">¥{{ item.sell_price }}</text>
					<text class="original-price">¥{{ item.market_price }}</text>
				</view>
				<text class="sales">已售{{ item.buy }}+</text>
			</view>
		</view>
	</view>
	<view v-if="loading" style="text-align:center;color:#999;padding:16rpx;">加载中...</view>
	<view v-if="finished" style="text-align:center;color:#999;padding:16rpx;">没有更多了</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	import { request } from '@/Requset/request'

	// 搜索
	const value = ref<string>('')

	function focus() {
		console.log('聚焦')
	}
	function blur() {
		console.log('失焦')
	}
	function search() {
		console.log('搜索')
	}
	function clear() {
		console.log('重置')
	}
	function cancel() {
		console.log('取消')
	}
	function change({ value }) {
		console.log('输入', value)
	}

	// 轮播图
	const current = ref<number>(0)
	const swiperList = ref<any[]>([])

	function handleClick(e) {
		// 跳转到对应的 url
		const item = swiperList.value[e]
		if (item && item.url) {
			// H5/小程序跳转
			window.open ? window.open(item.url) : uni.navigateTo({ url: item.url })
		}
	}
	function onChange(e) {
		console.log(e)
	}

	// 商品列表分页加载
	const productList = ref<any[]>([])
	const page = ref(1)
	const limit = 8
	const loading = ref(false)
	const finished = ref(false)

	// 获取轮播图数据
	onMounted(() => {
		request({
			url: 'api/getlunbo'
		}).then((res) => {
			if (res.data && res.data.status === 0) {
				swiperList.value = res.data.message
				// 打印轮播图图片地址
				console.log('轮播图图片地址:', swiperList.value.map(i => i.img))
			}
		})
		loadProducts()
	})

	// 加载商品数据
	function loadProducts() {
		if (loading.value || finished.value) return
		loading.value = true
		request({
			url: `api/recommend?page=${page.value}&limit=${limit}`
		}).then((res) => {
			if (res.data && res.data.status === 0) {
				const list = res.data.message
				// 打印商品图片地址
				console.log('商品图片地址:', list.map(i => i.img_url))
				if (list.length === 0) {
					finished.value = true
				} else {
					productList.value = [...productList.value, ...list]
					page.value++
				}
			}
		}).finally(() => {
			loading.value = false
		})
	}

	// 暴露方法给页面实例
	defineExpose({ loadProducts })

	// 商品点击事件
	function handleProductClick(item) {
		saveHistory(item)
		uni.navigateTo({
			url: `/pages/detail/detail?id=${item.id}`
		})
	}

	function saveHistory(item) {
		let history = uni.getStorageSync('history') || []
		history = history.filter(i => i.id !== item.id)
		history.unshift(item)
		if (history.length > 20) history = history.slice(0, 20)
		uni.setStorageSync('history', history)
	}

	// 历史记录
	const history = ref<any[]>([])

	onShow(() => {
		history.value = uni.getStorageSync('history') || []
	})

	function goDetail(item) {
		uni.navigateTo({
			url: `/pages/detail/detail?id=${item.id}`
		})
	}

	function goSearch() {
		uni.navigateTo({ url: '/pages/search/search' })
	}

	const iconList = [
		{ img: '/static/img/汇流箱.svg', text: '数码电器' },
		{ img: '/static/img/资讯.svg', text: '爱淘咨询' },
		{ img: '/static/img/分类.svg', text: '分类商品' },
		{ img: '/static/img/查看更多.svg', text: '查看更多' }
	]
</script>

<script lang="ts">
export default {
    // 页面触底事件
    onReachBottom() {
        // 通过 this.loadProducts() 调用 setup 里的方法
        // @ts-ignore
        this.loadProducts && this.loadProducts()
    }
}
</script>

<style scoped lang="scss">
	@import '@/common/common.scss';

	.navbar {
		display: flex;
		align-items: center;
		padding: 14rpx;
		background-color: #fff;
		box-shadow: 0 3rpx 3rpx rgba(0, 0, 0, 0.05);
	}

	.logo image {
		width: 48rpx;
		height: 48rpx;
		max-width: 10vw;
		max-height: 10vw;
	}

	.search-box {
		flex: 1;
		cursor: pointer;
		position: relative;
	}

	.fake-search {
		display: flex;
		align-items: center;
		background: #f5f5f5;
		border-radius: 32rpx;
		padding: 0 24rpx;
		height: 64rpx;
	}

	.fake-search-text {
		color: #999;
		font-size: 28rpx;
		margin-left: 12rpx;
	}

	/* 标签图标区域样式 */
	.icon-section {
		padding: 18rpx 0;
		background-color: #fff;
	}

	.icon-row {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		align-items: center;
		gap: 0; // 让每行紧凑排列
	}

	.icon-item {
		width: 25%; // 每行4个，自动适配
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 12rpx 0;
	}

	.icon-image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 16rpx;
		background: #f5f5f5;
		margin-bottom: 8rpx;
		object-fit: cover;
	}

	.icon-text {
		font-size: 24rpx;
		color: #666;
		text-align: center;
		margin-top: 2rpx;
	}

	/* 商品列表样式 */
	.product-list {
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start; // 或 space-between
		align-items: stretch;
		padding: 14rpx;
		gap: 14rpx;
		background-color: #fff;
	}

	.product-item {
		box-sizing: border-box;
		width: 48%; // 固定为两列
		margin-bottom: 14rpx;
		background-color: #fafafa;
		border-radius: 10rpx;
		overflow: hidden;
		box-shadow: 0 3rpx 9rpx rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: column;
	}

	.product-image {
		width: 100%;
		height: 28vw; // 用 vw 保证不同屏幕高度适配
		max-height: 260rpx;
		background-color: #fafafa; // 与卡片背景色一致
		object-fit: cover;
		display: block;
	}

	.product-info {
		padding: 10rpx;
	}

	.product-title {
		font-size: 16rpx;
		color: #333;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		line-height: 1.4;
	}

	.price-section {
		display: flex;
		align-items: center;
		margin-top: 7rpx;
	}

	.product-price {
		font-size: 18rpx;
		color: #f56c6c;
		font-weight: bold;
	}

	.original-price {
		font-size: 14rpx;
		color: #999;
		text-decoration: line-through;
		margin-left: 7rpx;
	}

	.sales {
		display: block;
		font-size: 14rpx;
		color: #999;
		margin-top: 5rpx;
	}
</style>